using System;
using System.Collections.Concurrent;
using System.IO;

namespace OracleInternal.Json.Binary
{
	internal class OsonGeneratorStatePool
	{
		internal volatile WeakReference<ConcurrentQueue<OsonGeneratorState>> m_queue;

		internal OsonGeneratorState GetState(Stream outStream)
		{
			ConcurrentQueue<OsonGeneratorState> queue = GetQueue();
			OsonGeneratorState result = null;
			queue?.TryDequeue(out result);
			if (result == null)
			{
				return new OsonGeneratorState(this, outStream);
			}
			result.Reset(outStream);
			return result;
		}

		internal void PutState(OsonGeneratorState state)
		{
			ConcurrentQueue<OsonGeneratorState> queue = GetQueue();
			if (queue == null)
			{
				queue = new ConcurrentQueue<OsonGeneratorState>();
				queue.Enqueue(state);
				m_queue = new WeakReference<ConcurrentQueue<OsonGeneratorState>>(queue);
			}
			else
			{
				queue.Enqueue(state);
			}
		}

		internal ConcurrentQueue<OsonGeneratorState> GetQueue()
		{
			ConcurrentQueue<OsonGeneratorState> target = null;
			m_queue?.TryGetTarget(out target);
			return target;
		}
	}
}
